import Vue from 'vue'
import Router from 'vue-router'
import store from '@/store/index'
// import Layout from '@/layout'

Vue.use(Router)
// import Layout from '@/layout'

export const constantRoutes = [
  // {
  //   path: '/',
  //   component: Layout,
  //   hidden: true,
  //   children: [{
  //     path: 'userManagement',
  //     name: 'userManagement',
  //     component: () => import('@/views/user/index.vue'),
  //     meta: { title: '人员管理', icon: 'people' }
  //   }]
  // },
  {
    path: '/login',
    component: () => import('@/views/login/index'),
    hidden: true
  },
  {
    path: '/404',
    component: () => import('@/views/404'),
    hidden: true
  }
]

const createRouter = () => new Router({
  mode: 'history',
  scrollBehavior: () => ({ y: 0 }),
  routes: constantRoutes
})

const router = createRouter()

router.beforeEach(async(to, from, next) => {
  if (store.getters.token) {
    if (store.getters.routes.length === 0) {
      await store.dispatch('user/generateRoutes')
      const routerss = store.getters.routes
      router.addRoutes([...routerss, { path: '*', redirect: '/404', hidden: true }])
      next(to.path) // 目的是让路由拥有信息 router的已知缺陷
    } else if (to.path === '/') {
      next('/userManagement')
    } else {
      next()
    }
  } else {
    if (to.path === '/login') {
      next()
    } else {
      next('/login')
    }
  }
})

export function resetRouter() {
  const newRouter = createRouter()
  router.matcher = newRouter.matcher
}

export default router
